package com.tudouji.project.organization.controller;

import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.IdUtils;
import com.tudouji.common.utils.SecurityUtils;
import com.tudouji.common.utils.poi.ExcelUtil;
import com.tudouji.framework.aspectj.lang.annotation.Log;
import com.tudouji.framework.aspectj.lang.enums.BusinessType;
import com.tudouji.framework.web.controller.BaseController;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.framework.web.page.TableDataInfo;
import com.tudouji.project.organization.domain.Department;
import com.tudouji.project.organization.domain.vo.DepartmentVo;
import com.tudouji.project.organization.service.IDepartmentService;
import com.tudouji.project.permission.domain.Salespermission;
import com.tudouji.project.permission.service.ISalespermissionService;
import com.tudouji.project.system.service.ITuserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 【tudouji部门】Controller
 *
 * @author tudouji
 * @date 2021-01-29
 */
@RestController
@RequestMapping("/organization/department")
public class DepartmentController extends BaseController
{
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private ISalespermissionService permissionService;
    @Autowired
    private ITuserService tuserService;
    /**
     * 通过组织查询部门
     */
    @RequestMapping(value = "findAll", method = RequestMethod.GET)
    public AjaxResult findAll(@ModelAttribute("department") Department department)
    {
        department.setStatus(1);
        List<Department> list = departmentService.selectDepartmentList(department);
        return AjaxResult.success(list);
    }
    /**
     * 部门列表
     */
    @PreAuthorize("@ss.hasPermi('organization:department:list')")
    @GetMapping("/listPC")
    public TableDataInfo listPC(Department department)
    {
        startPage();
        List<DepartmentVo> list = departmentService.findOrg(department);
        return getDataTable(list);
    }
    /**
     * 查询部门列表
     */
    @PreAuthorize("@ss.hasPermi('organization:department:list')")
    @GetMapping("/list")
    public TableDataInfo list(Department department)
    {
        startPage();
        department.setStatus(1);
        List<Department> list = departmentService.selectDepartmentList(department);
        return getDataTable(list);
    }

    /**
     * 导出部门列表
     */
    @PreAuthorize("@ss.hasPermi('organization:department:export')")
    @Log(title = "部门", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Department department)
    {
        List<Department> list = departmentService.selectDepartmentList(department);
        ExcelUtil<Department> util = new ExcelUtil<Department>(Department.class);
        return util.exportExcel(list, "department");
    }

    /**
     * 获取部门详细信息
     */
    @PreAuthorize("@ss.hasPermi('organization:department:query')")
    @GetMapping(value = "/{guid}")
    public AjaxResult getInfo(@PathVariable("guid") String guid)
    {
        return AjaxResult.success(departmentService.selectDepartmentById(guid));
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('organization:department:add')")
    @Log(title = "部门", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Department department)
    {
        department.setGuid(IdUtils.fastSimpleUUID());
        department.setCreatetime(DateUtils.getNowDate());
        department.setOperatorid(SecurityUtils.getLoginUser().getUser().getUserId().toString());
        return toAjax(departmentService.insertDepartment(department));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('organization:department:edit')")
    @Log(title = "部门", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Department department)
    {
        return toAjax(departmentService.updateDepartment(department));
    }

    /**
     * 启用/禁用
     */
    @Log(title = "部门", businessType = BusinessType.UPDATE)
    @RequestMapping(value = "on", method = RequestMethod.GET)
    public AjaxResult on(@RequestParam("guid") String guid)
    {
        return toAjax(departmentService.on(guid));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('organization:department:remove')")
    @Log(title = "部门", businessType = BusinessType.DELETE)
	@DeleteMapping("/{guids}")
    public AjaxResult remove(@PathVariable String[] guids)
    {
        return toAjax(departmentService.deleteDepartmentByIds(guids));
    }


    @GetMapping("/getDepartmentList")
    public AjaxResult getDepartmentList(Department department)
    {
        List<Department> list = departmentService.selectDepartmentList(department);
        return AjaxResult.success(list);
    }

    /**
     * @Author shaodong
     * @Description 通过权限获取部门
     * @Date 15:22 2021/4/23
     * @Param
     * @return
     **/
    @RequestMapping(value = "/getPermisForDepart", method = RequestMethod.GET)
    public AjaxResult getPermisForDepart(@RequestParam("functionTypes") String functionTypes, @RequestParam("departype") String departype){
        String tuserId = SecurityUtils.getLoginUser().getUser().getTuserId();
        try {
            if (StringUtils.isBlank(functionTypes)) {
                functionTypes = null;
            }
            return AjaxResult.success(permissionService.getPermssionForDepart(tuserId, functionTypes, departype));
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通过单一权限查找部门
     */
    @GetMapping("/findDepartment")
    public AjaxResult findDepartment(@RequestParam("permission") Integer permission) {
        try {
            List<Department> departs = new ArrayList<>();
            Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
            Salespermission sales = new Salespermission();
            sales.setUserId(userId);
            sales.setPermission(permission);
            sales.setStatus(1);
            List<Salespermission> sps = permissionService.selectSalespermissionList(sales);
            if (sps.size() == 0) {
                return  AjaxResult.success(departs);
            }
            String[] guids = new String[sps.size()];
            for (int i = 0; i < sps.size(); i++) {
                guids[i] = sps.get(i).getDepartid();
            }
            Department department = new Department();
            department.setIds(guids);
            departs = departmentService.selectDepartmentList(department);
            return AjaxResult.success(departs);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("findDepartment error");
        }
    }
}
